package com.usian.comment.service.impl;

import com.usian.comment.feign.UserFeign;
import com.usian.comment.repository.ApCommentLikeRepository;
import com.usian.comment.repository.ApCommentRepository;
import com.usian.comment.service.ApCommentService;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.comment.vo.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApCommentServiceImpl implements ApCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApCommentRepository apCommentRepository;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private GreeTextScan greeTextScan;

    @Autowired
    private ApCommentLikeRepository apCommentLikeRepository;

    private static final int DEFAULT_SIZE = 10;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        // 1.参数校验
        if (dto.getArticleId() == null || StringUtils.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(500, "评论内容不能超过140字！");
        }
        // 2.获取当前登录用户信息--->userid
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3.通过feign查询用户信息
        ApUser userInfo = userFeign.getUserById(user.getId());
        if (userInfo == null) {
            return ResponseResult.errorResult(500, "查询不到用户信息！");
        }
        // 4.调用阿里云安全内容检测
        boolean scanResult = handleTextInAliyun(dto.getContent());
        if (!scanResult) {
            return ResponseResult.errorResult(500, "评论内容违规，不能发布！");
        }
        // 5.调用api保存评论
        ApComment apComment = new ApComment();
        apComment.setAuthorId(userInfo.getId());
        apComment.setAuthorName(userInfo.getName());
        apComment.setImage(userInfo.getImage());
        apComment.setEntryId(dto.getArticleId());
        apComment.setType((short)0);
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short)0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        // 存入mongodb
        apCommentRepository.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult likeComment(CommentLikeDto dto) {
        // 1.参数校验
        if (StringUtils.isEmpty(dto.getCommentId())
                || dto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getOperation().shortValue() != 0 && dto.getOperation().shortValue() != 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApComment apComment = apCommentRepository.findById(dto.getCommentId()).get();
        if (dto.getOperation() == 0) {
            // 3.做点赞功能
            // 3.1.插入点赞数据
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation(dto.getOperation());
            apCommentLikeRepository.save(apCommentLike);
            // 3.2.更新评论点赞数

            apComment.setLikes(apComment.getLikes() + 1);
            apCommentRepository.save(apComment);
        } else {
            // 4.取消点赞功能
            // 4.1.更新评论点赞数 -1
            apComment.setLikes(apComment.getLikes() > 0 ? apComment.getLikes() - 1 : 0);
            apCommentRepository.save(apComment);
            // 4.2.删除点赞数据
            apCommentLikeRepository.deleteByAuthorIdAndCommentId(user.getId(), dto.getCommentId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult loadCommentList(CommentDto dto) {
        // 1.参数校验
        if (dto.getArticleId() == null || dto.getMinDate() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2.当前文章id进行检索，按照创建时间倒序，分页查询（默认10条数据）
        PageRequest pageRequest = PageRequest.of(0, DEFAULT_SIZE);
        List<ApComment> apCommentList =
                apCommentRepository.findByEntryIdOrderByCreatedTimeDesc(dto.getArticleId(), pageRequest);

        // 3.用户未登录 直接返回数据
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            return ResponseResult.okResult(apCommentList);
        }
        // 4.用户已登录，需要判断当前用户点赞了哪些评论
        // select   from ap_comment_like where comment_id in (apCommentList.ids) and author_id = userid
        List<String> commentIdList =
                apCommentList.stream().map(x -> x.getId()).collect(Collectors.toList());

        List<ApCommentLike> likeList =
                apCommentLikeRepository.findByCommentIdInAndAuthorId(commentIdList, user.getId());
        List<ApCommentVo> resultList = new ArrayList<>();
        if (apCommentList != null && likeList != null) {
            apCommentList.forEach(x -> {
                ApCommentVo vo = new ApCommentVo();
                BeanUtils.copyProperties(x, vo);
                for(ApCommentLike like : likeList) {
                    if (x.getId().equals(like.getCommentId())) {
                        vo.setOperation((short)0);
                        break;
                    }
                }
                resultList.add(vo);
            });
            return ResponseResult.okResult(resultList);
        } else {
            return ResponseResult.okResult(apCommentList);
        }
    }

    /**
     * 功能描述：阿里云文本检测功能
     * @param:
     * @return：
     * @auther：
     */
    private boolean handleTextInAliyun(String text) {
        boolean flag = true;
        try {
            Map map = greeTextScan.greeTextScan(text);
            String suggestion = (String)map.get("suggestion");
            // pass
            // block
            // review
            if (!suggestion.equals("pass")) {
                // block，审核状态变更成2，原因是内容违规
                if (suggestion.equals("block") || suggestion.equals("review")) {
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文本审核出现异常，信息如下:{}", e.getMessage());
            flag = false;
        }
        return flag;
    }
}
